<script setup lang="ts">
import AMapLoader from '@amap/amap-jsapi-loader';
import { shallowRef } from '@vue/reactivity';

const { proxy } = <any>getCurrentInstance();
const mapRef = ref<HTMLDivElement | null>(null);
const state = reactive<any>({
  map: null,
  polygon: null,
  polyEditor: null,
  path: [
    [118.882425, 31.884326],
    [118.883027, 31.882875],
    [118.883011, 31.881685],
    [118.882481, 31.87953],
    [118.888766, 31.8785],
    [118.894877, 31.889694],
    [118.889937, 31.88977],
    [118.887739, 31.887739],
    [118.884945, 31.885564],
    [118.883164, 31.884574],
  ],
});

let map = shallowRef(null);
const initMap = () => {
  AMapLoader.load({
    key: '6bf6c3b88542df1c14280c72f08d6134',
    version: '2.0',
    plugins: ['AMap.MarkerCluster', 'AMap.PolygonEditor'], // 需要使用的的插件列表，如比例尺 'AMap.Scale' 等
  })
    .then((AMap) => {
      state.map = new AMap.Map('mapContainer', {
        //设置地图容器id
        viewMode: '3D', //是否为3D地图模式
        zoom: 5, //初始化地图级别
        center: [118.78, 32.07], //初始化地图中心点位置
        // mapStyle: 'amap://styles/darkblue',
      });

      // 绘制多边形
      state.polygon = new AMap.Polygon({
        path: state.path,
      });
      state.map.add(state.polygon); // 将覆盖物/图层添加的地图上
      state.map.setFitView(); // 根据地图上添加的覆盖物分布情况，自动缩放地图到合适的视野级别
      state.polyEditor = new AMap.PolygonEditor(state.map);
      state.polyEditor.addAdsorbPolygons(state.polygon); // 添加吸附多边形

      state.polygon.on('dblclick', () => {
        console.log(1111);
        state.polyEditor.setTarget(state.polygon);
        state.polyEditor.open();
      });

      state.polyEditor.on('end', (data: any) => {
        // close 事件后执行
        console.log('data', data);
        // 可在此处执行保存方法
      });
    })
    .catch((e) => {
      console.log(e);
      throw '地图加载失败，请重新加载';
    });
};

const handleClose = () => {
  state.polyEditor.close();
};

onMounted(() => {
  initMap();
  // proxy.$emitter.on('headerOffsetHeight', (height: string) => {
  //   mapRef.value.setAttribute('style', height);
  // });
});
</script>

<template>
  <div class="relative h-full">
    <div id="mapContainer" ref="mapRef"></div>
    <button
      class="absolute top-5 right-5 py-2 px-3 text-base text-white bg-violet-700 hover:bg-violet-500 rounded-md"
      @click="handleClose"
    >
      结束编辑
    </button>
  </div>
</template>

<style scoped lang="scss">
#mapContainer {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: calc(100vh - 92px);
}
</style>
